<!-- 输入框 -->
<template>
  <div class="InputBox-container">
    <div v-for="(item, index) in inputDataRef" :key="index" class="main">
      <label class="label" >
      <span :style="{ width: `${item.title_width}px` }" class="text">{{
        item.title
      }}</span>
      <input
        :style="{ width: `${item.input_width}px` }"
        :required="item.err ? item.err[0].required : false"
        :type="item.type"
        class="txt"
        v-model="item[item.corresponding]"
        @blur="vaildate(item, index)"
        @input="synchronization"
      />
      
    </label>
    <span
        class="err"
        ref="err"
        v-if="item.err"
        :style="{ left: `${item.title_width + 10}px` }"
        ></span
      >
    </div>
    
  </div>
</template>

<script setup>
import { computed, ref } from "vue";
import { vaildates } from "@/util/validate.js";
import { deepClone } from "@/util/copy.js";
const props = defineProps({
  inputArr: {
    type: Array,
    default: () => [],
  },
});
const inputDataRef = computed(() => deepClone(props.inputArr)); // 深拷贝一份传入的数据
const err = ref([]); // 获取errDom

// 验证数据
function vaildate(item, index) {
  let i = index;
  if (!item.hasOwnProperty("err")) {
    return;
  }
  // errDom是否为0
  if (err.value.length === 0) {
    return;
  }
  // 如果errDom数组小于了index代表有些属性中没有规则验证
  if (err.value.length <= index) {
    i = err.value.length - 1;
  }
  const msg = vaildates(item);
  if(msg){
    err.value[i].style.display = "block";
    err.value[i].innerHTML = msg;
  }else {
    err.value[i].style.display = "none"
  }
}
const emit = defineEmits(["synchronization"])

// 同步数据
function synchronization(){
  let state = true;
  inputDataRef.value.forEach(item => {
    if(vaildates(item)){
      state = false
    }
  });
  if(state){
    emit("synchronization",inputDataRef.value)
  }
  
}



</script>

<style lang="less" scoped>
@import "@/styles/var.less";
.InputBox-container {
  width: 100%;

  .main{
    position: relative;
  }
  .label {
    display: block;
    height: 54px;
    
    display: flex;
    .text {
      font-size: 1.1em;
      position: relative;
      color: @gray;
      display: block;
      text-align-last: justify;
      text-align: justify;
      text-justify: distribute;
      &:has(+ input[required]):before {
        position: absolute;
        left: -10px;
        top: 0;
        content: "*";
        color: red;
      }
    }
    .txt {
      margin-left: 10px;
      height: 30px;
      font-size: 1em;
      background-color: transparent;
      border: 2px solid #bbbbbb;
      border-radius: 3px;
      outline: none;
      color: #fff;
      padding: 0 6px;
      &:focus {
        border-color: @frameColor1;
      }
    }
    
  }
  .err {
      display: block;
      position: absolute;
      bottom: 0;
      color: @danger;
      font-size: 12px;
      display: none;
    }
}
</style>